#include "bits/stdc++.h"
using namespace std;

int get_weights_sum(vector<vector<int>>& weights, vector<vector<int>>& memo, vector<vector<int>>& trace, int x, int y, int value){
  if(x<0 || x>= weights.size() || y<0 || y>= weights[0].size()) return -1;

  if(trace[x][y] != 0) return -1;
  
  if(memo[x][y] != 0) return memo[x][y];
  if(x == weights.size()-1 && y == weights.size()-1){
    memo[x][y] = weights[x][y];
    return memo[x][y];
  }

  trace[x][y] = 1;

  // int left=-1, right=-1, top=-1, bottom=-1;
  int left = get_weights_sum(weights, memo, trace, x, y-1, weights[x][y]);
  int right = get_weights_sum(weights, memo, trace, x, y+1, weights[x][y]);
  int top = get_weights_sum(weights, memo, trace, x-1, y, weights[x][y]);
  int bottom = get_weights_sum(weights, memo, trace, x+1, y, weights[x][y]);
  int left_top = get_weights_sum(weights, memo, trace, x-1, y-1, weights[x][y]);
  int right_top = get_weights_sum(weights, memo, trace, x+1, y-1, weights[x][y]);
  int left_bottom = get_weights_sum(weights, memo, trace, x-1, y+1, weights[x][y]);
  int right_bottom = get_weights_sum(weights, memo, trace, x+1, y+1, weights[x][y]);

  int temp = INT_MAX;
  if(left == -1 && right == -1 && top == -1 && bottom == -1) return -1;
  else{
    if(left != -1) temp = min(temp, left);
    if(right != -1) temp = min(temp, right);
    if(top != -1) temp = min(temp, top);
    if(bottom != -1) temp = min(temp, bottom);
    if(left_top != -1) temp = min(temp, left_top);
    if(right_top != -1) temp = min(temp, right_top);
    if(left_bottom != -1) temp = min(temp, left_bottom);
    if(right_bottom != -1) temp = min(temp, right_bottom);
  }

  trace[x][y] = 0;

  temp+=weights[x][y];
  if(weights[x][y] == value) temp-=1;
  memo[x][y] = temp;

  return memo[x][y];
  
}

int main(int argc, char* argv[]){

  int M, N;
  cin >> M >> N;

  vector<vector<int>> weights(M, vector<int>(N));
  for(int i=0; i<M; i++){
    for(int j=0; j<N; j++){
      cin >> weights[i][j];
    }
  }

  vector<vector<int>> memo(M, vector<int>(N, 0));
  vector<vector<int>> trace(M, vector<int>(N, 0));
  
  get_weights_sum(weights, memo, trace, 0, 0, -1);

  cout<<memo[0][0]<<endl;

}